package com.demo.key.server

import com.demo.key.util.Conf0822
import com.demo.key.util.getDelayByServerHost
import com.github.shadowsocks.database.Profile
import com.github.shadowsocks.database.ProfileManager
import com.google.firebase.ktx.Firebase
import com.google.firebase.remoteconfig.ktx.remoteConfig
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.json.JSONObject

object ServerInfo0822Manager {
    private val localServerList= arrayListOf<Server0822Entity>()
    private val confServerList= arrayListOf<Server0822Entity>()
    private val confCityList= arrayListOf<String>()


    fun getServerList() = confServerList.ifEmpty { localServerList }

    fun getSuperFastServer():Server0822Entity? {
        val serverList = getServerList()
        if (!confCityList.isNullOrEmpty()){
            val filter = serverList.filter { confCityList.contains(it.city_key0822) }
            if (!filter.isNullOrEmpty()){
                return filter.randomOrNull()
            }
        }
        return serverList.randomOrNull()
    }

    fun createFastServer()=Server0822Entity(country_key0822 = "Super Fast Server")

    fun readLocalServerInfo(){
        localServerList.clear()
        localServerList.addAll(parseServerJson(Conf0822.SERVER_CONF0822))
    }

    fun readFirebaseInfo(){
        readConfServerInfo(Conf0822.SERVER_CONF0822)
        readConfCityInfo(Conf0822.CITY_CONF0822)
        readConfAdInfo(Conf0822.AD_CONF0822)

//        val remoteConfig = Firebase.remoteConfig
//        remoteConfig.fetchAndActivate().addOnCompleteListener {
//            if (it.isSuccessful){
//                readConfServerInfo(remoteConfig.getString("key0822_server"))
//                readConfCityInfo(remoteConfig.getString("key0822_city"))
//                readConfAdInfo(remoteConfig.getString("key0822_ad"))
//            }
//        }

    }

    private fun readConfServerInfo(json: String){
        confServerList.clear()
        confServerList.addAll(parseServerJson(json))
    }

    private fun readConfCityInfo(json: String){
        try {
            confCityList.clear()
            val jsonArray = JSONObject(json).getJSONArray("key0822_city")
            for (index in 0 until jsonArray.length()){
                confCityList.add(jsonArray.optString(index))
            }
        }catch (e:Exception){}
    }

    private fun readConfAdInfo(json: String){
        MMKV.defaultMMKV().encode("ad_json",json)
    }

    private fun parseServerJson(json:String):ArrayList<Server0822Entity>{
        val list= arrayListOf<Server0822Entity>()
        try {
            val jsonArray = JSONObject(json).getJSONArray("key0822_server")
            for (index in 0 until jsonArray.length()){
                val jsonObject = jsonArray.getJSONObject(index)
                val server0822Entity = Server0822Entity(
                    jsonObject.optString("pwd_key0822"),
                    jsonObject.optString("method_key0822"),
                    jsonObject.optInt("port_key0822"),
                    jsonObject.optString("country_key0822"),
                    jsonObject.optString("city_key0822"),
                    jsonObject.optString("host_key0822"),
                )
                list.add(server0822Entity)
            }
            GlobalScope.launch {
                list.forEach {
                    writeServerToLocal(it)
                    it.speed=getDelayByServerHost(it.host_key0822)
                }
            }
        }catch (e:Exception){ }
        return list
    }

    private fun writeServerToLocal(server0822Entity: Server0822Entity){
        val profile = Profile(
            id = 0L,
            name = "${server0822Entity.country_key0822} - ${server0822Entity.city_key0822}",
            host = server0822Entity.host_key0822,
            remotePort = server0822Entity.port_key0822,
            password = server0822Entity.pwd_key0822,
            method = server0822Entity.method_key0822
        )

        var id:Long?=null
        ProfileManager.getActiveProfiles()?.forEach {
            if (it.remotePort==profile.remotePort&&it.host==profile.host){
                id=it.id
                return@forEach
            }
        }
        if (null==id){
            ProfileManager.createProfile(profile)
        }else{
            profile.id=id!!
            ProfileManager.updateProfile(profile)
        }
    }

    fun getServerInfoId(server0822Entity: Server0822Entity):Long{
        ProfileManager.getActiveProfiles()?.forEach {
            if (it.host==server0822Entity.host_key0822&&it.remotePort==server0822Entity.port_key0822){
                return it.id
            }
        }
        return 0L
    }

    fun checkServerIsFast(server0822Entity: Server0822Entity):Boolean{
        return server0822Entity.country_key0822=="Super Fast Server"&&server0822Entity.host_key0822.isEmpty()
    }

    fun getServerSpeed(server0822Entity: Server0822Entity):Int{
        if (checkServerIsFast(server0822Entity)){
            val sortedByDescending = localServerList.sortedByDescending { it.speed }
            return sortedByDescending.first().speed
        }else{
            return server0822Entity.speed
        }
    }
}